<script setup>
import FieldSet from "/src/views/crm/componentsNew/FieldSetNew/index.vue";
import WkFieldView from "components/NewCom/WkForm/WkFieldView.vue";
import BusinessCheck from "@/views/crm/customer/comp/BusinessCheck.vue";
import WkEmpty from "@/szcomponent/WkEmpty/index.vue";
import {
  crmConfigKey, crmOptionChangeKey,
  crmOptionKey, elTableOptionChangeKey,
  elTableOptionKey, fieldAndListOptionKey,
  mainTableKey, pageOptionKey,
  tableHeadOptionKey,
} from "/src/views/crm/componentsNew/SzCrud/keys.js";
import {ref, nextTick, watch, onMounted, computed, reactive} from "vue"
import {useErpUserStore} from "/src/store/modules/usererp.js";
import {useSzTable} from "@/views/crm/componentsNew/SzCrud/table/useSzTable.js";
import {useSzColumn} from "@/views/crm/componentsNew/SzCrud/table/useSzColumn.js";
import {useBusinessCheck} from "@/views/crm/componentsNew/SzCrud/table/useBusinessCheck.js";
import {useCheckStatusHook} from "@/hooks/useCheckStatusHook.js";

const properties = defineProps({
  // 筛选配置
  props: {
    type: Object,
    default: null
  },
  // 筛选选择的数据
  selectedData: Array,
  cellClassName: Function,
  headerCellClassName: Function
})

const emits = defineEmits(['createClick', 'setSelection', 'getFieldList', 'getList'])

const mainTableFunction = inject(mainTableKey)
const refCrmTable = ref()
onMounted(() => {
  mainTableFunction(refCrmTable);
})

const config = inject(crmConfigKey)

const pageOption = inject(pageOptionKey)

const tableHeadOption = inject(tableHeadOptionKey)

const crmOption = inject(crmOptionKey)
const crmOptionChange = inject(crmOptionChangeKey)

const elTableOption = inject(elTableOptionKey)
const elTableOptionChange = inject(elTableOptionChangeKey)

const fieldAndListOption = inject(fieldAndListOptionKey)

const hookSzTable = useSzTable()


/**
 * 列表操作
 * @param {*} row
 * @param {*} column
 * @param {*} event
 */
function handleRowClick(row, column, event) {
  // 抽取了函数
  let crmOptionTemp = {}
  crmOptionTemp.showDview = crmOption.showDview
  crmOptionTemp.crmType = crmOption.crmType

  let elTableOptionTemp = {}
  elTableOptionTemp.rowID = ''
  elTableOptionTemp.rowType = ''

  hookSzTable.bizHandleRowClick(crmOptionTemp, elTableOptionTemp, fieldAndListOption, row, column)

  // 更新crmOption
  crmOptionChange("crmType", crmOptionTemp.crmType)
  crmOptionChange("showDview", crmOptionTemp.showDview)

  // 更新elTableOption
  elTableOptionChange("rowID", elTableOptionTemp.rowID)
  elTableOptionChange("rowType", elTableOptionTemp.rowType)

}

function dealIcon(status) {
  return hookSzColumnSingle.dealIcon(status)
}

function dealName(status) {
  return hookSzColumnSingle.dealName(status)
}

/**
 * 当拖动表头改变了列的宽度的时候会触发该事件。更改配置中的列宽度
 * @param {*} newWidth
 * @param {*} oldWidth
 * @param {*} column
 * @param {*} event
 */
function handleHeaderDragend(newWidth, oldWidth, column, event) {
  hookSzTable.bizHandleHeaderDragend(crmOption, fieldAndListOption, newWidth, oldWidth, column)
}

/**
 * 勾选操作
 * @param {*} val
 */
function handleSelectionChange(val) {
  const mainTable = getMainTable()
  hookSzTable.bizHandleSelectionChange(elTableOption, config, mainTable, val)
}

const crm = computed(() => {
  const erpUserStore = useErpUserStore();
  return erpUserStore.crm;
})

const saveAuth = computed(() => {
  if (crmOption.isSeas) {
    return false
  }

  return crm.value[crmOption.crmType] && crm.value[crmOption.crmType].save
})

watch(() => properties.selectedData, (newVal) => {
  // 筛选默认值勾选
  elTableOption.ignoreSelectedChange = true
  if (newVal) {
    let valueEquals = true
    if (newVal.length !== elTableOption.selectionList.length) {
      valueEquals = false
    } else {
      for (let i = 0; i !== newVal.length; ++i) {
        if (newVal[i][`${crmOption.crmType}Id`] !== elTableOption.selectionList[i][`${crmOption.crmType}Id`]) {
          valueEquals = false
          break
        }
      }
    }

    if (!valueEquals) {
      emits("setSelection", elTableOption.selectedData)
      // setSelections(elTableOption.selectedData)
    }
  }

  nextTick(() => {
    elTableOption.ignoreSelectedChange = false
  })
})


const hookSzColumnSingle = useSzColumn()
const hookCheckStatusMixin = useCheckStatusHook()

function fieldFormatter(row, column, cellValue, field) {
  return hookSzColumnSingle.fieldFormatter(row, column, cellValue, field)
}


/**
 * 刷新数据
 */
function refreshList() {
  pageOption.currentPage = 1
  emits('getFieldList', false)
  // getFieldList()
}

/**
 * 获取table
 */
function getMainTable() {
  // let table = null
  // this.$children.forEach(item => {
  //   if (item.$options && item.$options.name === 'ElTable') {
  //     table = item
  //   }
  // })
  // return table
  return refCrmTable;
}

const hookBusinessCheckSingle = useBusinessCheck()

function relativeBusinessClick(data) {
  hookBusinessCheckSingle.relativeBusinessClick(crmOption, elTableOption, data)
}

function businessClose(e, scope) {
  hookBusinessCheckSingle.businessClose(e, scope)
}

function businessCheckClick(e, scope) {
  hookBusinessCheckSingle.businessCheckClick(e, scope)
}

/** 自定义字段管理 */
function setSave() {
  emits("getFieldList", true)
  // getFieldList(true)
}

/**
 * 字段排序
 */
function sortChange(column, prop, order) {
  hookSzTable.sortChange(crmOption, pageOption, column, prop, order)
  emits('getList')
  // getList()
}

/**
 * 切换关注状态
 * @param index
 * @param status
 */
function toggleStar(data) {
  hookSzColumnSingle.toggleStar(crmOption, data)
}

/**
 * 更新表高
 */
function updateTableHeight() {
  if (config.value && config.value.tableHeight) {
    nextTick(() => {
      tableHeight.value =
          tableHeadOption.filterObj.length > 0
              ? config.value.tableHeight - 60
              : config.value.tableHeight
    })
  } else {
    let offsetHei = document.documentElement.clientHeight
    let removeHeight = tableHeadOption.filterObj.length > 0 ? 295 : 235
    tableHeight.value = offsetHei - removeHeight
  }
}


/**
 * 切换某一行的选中状态
 */
function toggleRowSelection(rowKey, rowId, selected) {
  nextTick(() => {
    const removeItem = elTableOption.selectionList.find(item => item[rowKey] === rowId)

    if (removeItem) {
      getMainTable().toggleRowSelection(removeItem, selected)
    }
  })
}


/**
 * 新建点击
 */
function createClick() {
  emits('createClick')
  // createType.value = crmType.value
  // createAction.value = {
  //   type: 'save',
  //   id: '',
  //   data: {}
  // }
  // createShow.value = true
}


const starShow = computed(() => {
  return crmOption.crmType == 'leads' || crmOption.crmType == 'customer'
      || crmOption.crmType == 'contacts' || crmOption.crmType == 'business'
})

</script>

<template>
  <!--header-dragend 当拖动表头改变了列的宽度的时候会触发该事件-->
  <el-table v-loading="crmOption.loading"
            id="crm-table"
            ref="refCrmTable"
            :row-height="40"
            :data="fieldAndListOption.dataList"
            :height="crmOption.tableHeight"
            :cell-class-name="cellClassName"
            :header-cell-class-name="headerCellClassName"
            :row-key="`${crmOption.crmType}Id`"
            :class="[{'no-all-selection': config.radio}]"
            class="n-table--border"
            stripe
            border
            highlight-current-row
            style="width: 100%"
            @row-click="handleRowClick"
            @sort-change="sortChange"
            @header-dragend="handleHeaderDragend"
            @selection-change="handleSelectionChange">
    <!-- 选择框     -->
    <el-table-column show-overflow-tooltip reserve-selection type="selection" align="center" width="55"/>
    <!-- 商机信息，只有客户管理才有 -->
    <!--prop 表示字段名称 对应列内容的字段名-->
    <el-table-column v-if="crmOption.crmType =='customer'" :resizable="false"
                     prop="businessCheck" fixed label=""
                     width="45">
      <template v-slot:header="scope">
        <i class="wk wk-business" style="cursor: not-allowed; color: #9DA9C2;"/>
      </template>
      <template v-slot="scope">
        <!-- 以弹出框的形式显示商机信息，包括商机个数、商机名称、商机金额、客户名称、商机状态组、状态-->
        <el-popover ref="businessCheckRef"
                    :disabled="scope.row.businessCount == 0"
                    placement="right" :offset="20"
                    width="500" trigger="click">
          <BusinessCheck :data="scope" :show="scope.row.show"
                         @click="relativeBusinessClick"
                         @close="businessClose($event, scope)"/>
          <template v-slot:reference>
            <i :style="{'opacity' :scope.row.businessCount > 0 ? 1 : 0}"
               class="wk wk-business" style="color: #FC6E51"
               @click="businessCheckClick($event, scope)"/>
          </template>
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column v-for="(item, index) in fieldAndListOption.fieldList" :key="index"
                     :fixed="index==0"
                     :prop="item.prop"
                     :label="item.label"
                     :width="item.width"
                     :sortable="item.prop != 'poolDay' ? 'custom' : false"
                     show-overflow-tooltip>
      <template v-slot="{ row, column, $index }">
        <!--成交状态-->
        <template v-if="item.prop == 'dealStatus'">
          <i :class="dealIcon(row[item.prop])"/>
          <span>{{ dealName(row[item.prop]) }}</span>
        </template>
        <!--锁定状态-->
        <template v-else-if="item.prop == 'status'">
          <i v-if="row.status == 2" class="wk wk-circle-password customer-lock"/>
        </template>
        <template v-if="item.prop == 'checkStatus'">
          <span :style="{backgroundColor: hookCheckStatusMixin.getStatusColor(row.checkStatus)}" class="status-mark"/>
          <span>{{ hookCheckStatusMixin.getStatusName(row.checkStatus) }}</span>
        </template>
        <template v-else-if="item.prop == 'receivedStatus'">
          {{ hookCheckStatusMixin.getPlanReceivablesStatusName(row.receivedStatus) }}
        </template>
        <WkFieldView v-else v-bind:props="item" v-bind:form-type="item.formType" v-bind:value="row[column.property]">
          <template v-slot:default="{ data }">
            {{ fieldFormatter(row, column, row[column.property], item) }}
          </template>
        </WkFieldView>
      </template>
    </el-table-column>
    <el-table-column/>
    <el-table-column v-if="starShow" label="关注" align="center" fixed="right" width="60">
      <template v-slot="scope">
        <el-tooltip :content="scope.row.star == 0 ? '添加关注' : '取消关注'" effect="dark" placement="top">
          <i :class="{active: scope.row.star != 0}"
             class="wk wk-focus-on focus-icon" @click="toggleStar(scope.row, crmOption.crmType)"/>
        </el-tooltip>
      </template>
    </el-table-column>
    <!--自定义字段管理，目前看来没有显示出来-->
    <el-table-column :resizable="false" fixed="right" width="40">
      <template v-slot:header="{ column, $index }">
        <FieldSet v-bind:crm-type="crmOption.crmType" v-on:change="setSave"/>
      </template>
    </el-table-column>
    <template v-slot:empty>
      <WkEmpty :props="{buttonTitle: '新建',showButton: saveAuth}" @click="createClick"/>
    </template>
  </el-table>
</template>

<style scoped lang="scss">
@import '../../../styles/table';
</style>